package com.godyao.mall.feign.intercept;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.godyao.mall.core.utils.RequestContextUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 解决feign中令牌中继问题
 * @author godyao
 * @date 2022/3/31
 */
@Component
@Slf4j
public class FeignRequestIntercept implements RequestInterceptor {
    private static final String TOKEN_KEY = "access-token";
    private static final String GRAY_KEY = "access-token";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        final HttpServletRequest request = RequestContextUtils.getRequest();
        if (ObjectUtil.isNotNull(request)) {
            Map<String, String> headersMap = getHeaders(request);
            for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                requestTemplate.header(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * 获取所有的请求头
     * @param request
     * @return
     */
    private Map<String, String> getHeaders(HttpServletRequest request) {
        final Map<String, String> headersMap = new LinkedHashMap<>();
        final Enumeration<String> headerEnumeration = request.getHeaderNames();
        if (Objects.nonNull(headerEnumeration)) {
            while (headerEnumeration.hasMoreElements()) {
                final String headerKey = headerEnumeration.nextElement();
                // 需要中继的请求头 令牌信息和会读发布信息
                if (StrUtil.equals(TOKEN_KEY, headerKey)) {
                    headersMap.put(headerKey, request.getHeader(headerKey));
                }
                if (StrUtil.equals(GRAY_KEY, headerKey)) {
                    // TODO 保存灰度发布的标记
                    //RibbonC
                    headersMap.put(headerKey, request.getHeader(headerKey));
                }

            }
        }
        return headersMap;
    }
}
